package com.szgr.baoyin.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.model.CardMessage;
import com.szgr.baoyin.model.CardType;
import com.szgr.baoyin.model.InvoiceListItem;
import com.szgr.baoyin.myview.Tag;
import com.szgr.baoyin.myview.WheelView;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.DialogUtils;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.RLog;
import com.szgr.baoyin.utils.ToastUtils;
import com.szgr.baoyin.utils.ViewFindUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ApplyCardActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {

    private InvoiceListItem invoiceListItem;
    private EditText et_01;
    private EditText et_02;
    private EditText et_03;
    private EditText et_04;
    private EditText et_05;
    private EditText et_06;
    private EditText et_07;
    private EditText et_08;
    private EditText et_09;
    private EditText et_10;
    private String cardId = "1";
    private String enterpriseId;
    private String invoiceId;
    private EditText et_name;
    private EditText et_card;
    private EditText et_phone;
    private EditText et_company;
    private EditText et_companyAddress;
    private EditText et_emailAddress;
    private EditText et_email;
    private List<CardType> types;
    private LinearLayout menuView;
    private Dialog menuDialog;
    private int index = 1;
    private WheelView wheelView;
    private TextView tv_cardName;
    private TextView tv_cardMoney;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 555:
                    String paySn = (String) msg.obj;
                    if(enterpriseId == null){
                        cardMsg = new CardMessage();
                        cardMsg.setEnterprise_author(MyTool.getText(et_name));
                        cardMsg.setEnterprise_author_idcard(MyTool.getText(et_card));
                        cardMsg.setEnterprise_name(MyTool.getText(et_company));
                        cardMsg.setEnterprise_phone(MyTool.getText(et_phone));
                        cardMsg.setEnterprise_address(MyTool.getText(et_companyAddress));
                        cardMsg.setEnterprise_address_recv(MyTool.getText(et_emailAddress));
                        cardMsg.setEnterprise_email(MyTool.getText(et_email));
                    }
                    Intent intent = new Intent(ApplyCardActivity.this,ApplyCardDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("cardMsg",cardMsg);
                    bundle.putSerializable("invoice", invoiceListItem);
                    bundle.putSerializable("cardType", cardType);
                    bundle.putString("pay_sn",paySn);
                    intent.putExtra("bundle",bundle);
                    startActivity(intent);
                    break;
                case 666:
                    DialogUtils.hideLoadingDialog();
                    cardMsg = cardMessages.get(0);
                    enterpriseId = cardMsg.getEnterprise_id();
                    et_name.setText(cardMsg.getEnterprise_author());
                    et_card.setText(cardMsg.getEnterprise_author_idcard());
                    et_phone.setText(cardMsg.getEnterprise_phone());
                    et_company.setText(cardMsg.getEnterprise_name());
                    et_companyAddress.setText(cardMsg.getEnterprise_address());
                    et_emailAddress.setText(cardMsg.getEnterprise_address_recv());
                    et_email.setText(cardMsg.getEnterprise_email());
                    break;
                case 777:
                    DialogUtils.hideLoadingDialog();
                    break;
            }
        }
    };
    private CardMessage cardMsg;
    private CardType cardType;
    private TextView tv_cardLevel;
    private TextView tv_cardMinus1;
    private TextView tv_cardMinus2;
    private View btn_submit;
    private List<CardMessage> cardMessages;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_apply_card);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("申请都银卡会员");
    }

    @Override
    public void initView() {
        et_name = (EditText) findViewById(R.id.apply_name);
        et_card = (EditText) findViewById(R.id.buy_protect_company1);
        et_phone = (EditText) findViewById(R.id.card_phone);
        et_company = (EditText) findViewById(R.id.card_company);
        et_companyAddress = (EditText) findViewById(R.id.card_address);
        et_emailAddress = (EditText) findViewById(R.id.buy_protect_address1);
        et_email = (EditText) findViewById(R.id.buy_protect_faren1);

        et_01 = (EditText) findViewById(R.id.invoice_01);
        et_02 = (EditText) findViewById(R.id.invoice_02);
        et_03 = (EditText) findViewById(R.id.invoice_03);
        et_04 = (EditText) findViewById(R.id.invoice_04);
        et_05 = (EditText) findViewById(R.id.invoice_05);
        et_06 = (EditText) findViewById(R.id.invoice_06);
        et_07 = (EditText) findViewById(R.id.invoice_07);
        et_08 = (EditText) findViewById(R.id.invoice_08);
        et_09 = (EditText) findViewById(R.id.invoice_09);
        et_10 = (EditText) findViewById(R.id.invoice_10);

        findViewById(R.id.go_choose_invoice).setOnClickListener(this);
        findViewById(R.id.go_choose_msg).setOnClickListener(this);
        findViewById(R.id.choose_card_type).setOnClickListener(this);
        findViewById(R.id.choose_card_type1).setOnClickListener(this);
        findViewById(R.id.choose_card_type2).setOnClickListener(this);
        btn_submit = findViewById(R.id.my_order_detail_submit1);
        btn_submit.setOnClickListener(this);
        findViewById(R.id.back).setOnClickListener(this);

        tv_cardName = (TextView) findViewById(R.id.pay_card_type);
        tv_cardMoney = (TextView) findViewById(R.id.pay_card_money);
        tv_cardLevel = (TextView) findViewById(R.id.card_level);
        tv_cardMinus1 = (TextView) findViewById(R.id.card_minus1);
        tv_cardMinus2 = (TextView) findViewById(R.id.card_minus2);

        CheckBox cb_btn = (CheckBox) findViewById(R.id.yes_or_no);
        cb_btn.setOnCheckedChangeListener(this);

        cardType();
        initDialog("选择充值卡");

        getCard();
    }

    private void getCard() {
        DialogUtils.showLoadingDialog(this,"正在获取信息...");
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_LOAD_CARD,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        RLog.s("---load--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            JSONArray enterprise_list = datas.getJSONArray("enterprise_list");
                            Gson gson = new Gson();
                            cardMessages = gson.fromJson(enterprise_list.toString(),new TypeToken<List<CardMessage>>(){}.getType());
                            if(cardMessages != null && cardMessages.size() == 0){
                                mHandler.obtainMessage(777).sendToTarget();
                            }else {
                                mHandler.obtainMessage(666).sendToTarget();
                            }
                        } catch (JSONException e) {
                            mHandler.obtainMessage(777).sendToTarget();
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mHandler.obtainMessage(777).sendToTarget();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.go_choose_msg:
                Intent intent1 = new Intent(this, CardMessageActivity.class);
                startActivityForResult(intent1, 23);
                break;
            case R.id.go_choose_invoice:
                Intent intent = new Intent(this, InvoiceActivity.class);
                intent.putExtra("isFromCard",true);
                startActivityForResult(intent, 22);
                break;
            case R.id.my_order_detail_submit1:
                if(MyTool.isEmpty(et_name) || MyTool.isEmpty(et_card) || MyTool.isEmpty(et_phone)
                        || MyTool.isEmpty(et_company) || MyTool.isEmpty(et_companyAddress) || MyTool.isEmpty(et_emailAddress)
                        || MyTool.isEmpty(et_email) || MyTool.isEmpty(et_01) || MyTool.isEmpty(et_02)
                        || MyTool.isEmpty(et_03) || MyTool.isEmpty(et_04) || MyTool.isEmpty(et_05)
                        || MyTool.isEmpty(et_06) || MyTool.isEmpty(et_07) || MyTool.isEmpty(et_08)
                        || MyTool.isEmpty(et_09) || MyTool.isEmpty(et_10) || TextUtils.isEmpty(tv_cardName.getText().toString().trim())){
                    ToastUtils.showToast("请完整填写信息");
                }else {
                    submitCard();
                }
                break;
            case R.id.back:

                break;
            case R.id.choose_card_type:
            case R.id.choose_card_type1:
            case R.id.choose_card_type2:
                List<String> strs = new ArrayList<>();
                for (CardType ct : types) {
                    strs.add(ct.getCard_name());
                }
                if(strs.size() > 0) {
                    wheelView.setItems(strs);
                    wheelView.setSeletion(0);
                    menuDialog.show();
                }
                break;
        }
    }

    private void submitCard() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_APPLY_CARD,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        RLog.s("----card apply--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            String pay_sn = datas.getString("pay_sn");
                            mHandler.obtainMessage(555,pay_sn).sendToTarget();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("card_id",cardId);

                if(enterpriseId == null){
                    map.put("enterprise_id","0");
                    map.put("enterprise_author", MyTool.getText(et_name));
                    map.put("enterprise_author_idcard",MyTool.getText(et_card));
                    map.put("enterprise_phone",MyTool.getText(et_phone));
                    map.put("enterprise_name",MyTool.getText(et_company));
                    map.put("enterprise_address",MyTool.getText(et_companyAddress));
                    map.put("enterprise_address_recv",MyTool.getText(et_emailAddress));
                    map.put("enterprise_email",MyTool.getText(et_email));
                }else{
                    map.put("enterprise_id",enterpriseId);
                }

                if(invoiceId != null){
                    map.put("invoice_id",invoiceId);
                    map.put("invoice_type", "2");
                }else {
                    map.put("invoice_id","0");
                    map.put("invoice_type", "2");
                    map.put("inv_company", MyTool.getText(et_01));
                    map.put("inv_code", MyTool.getText(et_02));
                    map.put("inv_reg_addr", MyTool.getText(et_03));
                    map.put("inv_reg_phone", MyTool.getText(et_04));
                    map.put("inv_reg_bname", MyTool.getText(et_05));
                    map.put("inv_reg_baccount",MyTool.getText(et_06) );
                    map.put("inv_rec_name",MyTool.getText(et_07));
                    map.put("inv_rec_mobphone", MyTool.getText(et_08));
                    map.put("inv_rec_province", MyTool.getText(et_09));
                    map.put("inv_goto_addr",MyTool.getText(et_10));
                }
                map.put("key",MyApplication.getmInstance().getKey());

                RLog.s("---params-->" + map.toString());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private void cardType() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_APPLY_CARD_TYPE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        RLog.s("----card type--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            JSONArray card_list = datas.getJSONArray("card_list");
                            Gson gson = new Gson();
                            types = gson.fromJson(card_list.toString(),new TypeToken<List<CardType>>(){}.getType());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key", MyApplication.getmInstance().getKey());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(data != null){
            switch (resultCode){
                case 33:
                    invoiceListItem = (InvoiceListItem) data.getSerializableExtra("inv_id");
                    invoiceId = invoiceListItem.getInv_id();
                    et_01.setText(invoiceListItem.getInv_company());
                    et_02.setText(invoiceListItem.getInv_code());
                    et_03.setText(invoiceListItem.getInv_reg_addr());
                    et_04.setText(invoiceListItem.getInv_reg_phone());
                    et_05.setText(invoiceListItem.getInv_reg_bname());
                    et_06.setText(invoiceListItem.getInv_reg_baccount());
                    et_07.setText(invoiceListItem.getInv_rec_name());
                    et_08.setText(invoiceListItem.getInv_rec_mobphone());
                    et_09.setText(invoiceListItem.getInv_rec_province());
                    et_10.setText(invoiceListItem.getInv_goto_addr());
                    break;
                case 34:
                    cardMsg = (CardMessage) data.getSerializableExtra("cardMsg");
                    enterpriseId = cardMsg.getEnterprise_id();
                    et_name.setText(cardMsg.getEnterprise_author());
                    et_card.setText(cardMsg.getEnterprise_author_idcard());
                    et_phone.setText(cardMsg.getEnterprise_phone());
                    et_company.setText(cardMsg.getEnterprise_name());
                    et_companyAddress.setText(cardMsg.getEnterprise_address());
                    et_emailAddress.setText(cardMsg.getEnterprise_address_recv());
                    et_email.setText(cardMsg.getEnterprise_email());
                    break;
            }
        }
    }

    public void initDialog(String title){
        menuView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.layout_wheel_view,null);
        View confirm = menuView.findViewById(R.id.confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cardType = types.get(index - 1);
                String str = cardType.getCard_name();
                cardId = cardType.getCard_id();

                tv_cardName.setText(str);
                tv_cardMoney.setText(cardType.getCard_limit());
                tv_cardLevel.setText("Lv " + cardType.getCard_id());
                List<CardType.CardConfig> card_config = cardType.getCard_config();
                for (CardType.CardConfig cc : card_config) {
                    if("12".equals(cc.getStore_goods_class())){
                        tv_cardMinus1.setText("配件 " + MyTool.formatDouble(Double.parseDouble(cc.getCard_discount()) * 10) + "折");
                    }else if("13".equals(cc.getStore_goods_class())){
                        tv_cardMinus2.setText("维保 " + MyTool.formatDouble(Double.parseDouble(cc.getCard_discount()) * 10) + "折");
                    }
                }

                menuDialog.dismiss();
                index = 1;
            }
        });
        View cancel = menuView.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuDialog.dismiss();
                index = 1;
            }
        });
        TextView tv_title = (TextView) menuView.findViewById(R.id.title);
        tv_title.setText(title);
        wheelView = (WheelView) menuView.findViewById(R.id.wheel_view);

        wheelView.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                index = selectedIndex;
            }
        });
        menuDialog = MyTool.getMenuDialog(this, menuView);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(isChecked){
            btn_submit.setEnabled(true);
        }else{
            btn_submit.setEnabled(false);
        }
    }
}
